package com.cxh.controller.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cxh.base.BaseController;
import com.cxh.entity.CarDiscount;
import com.cxh.entity.CarDiscountDetail;
import com.cxh.entity.SysUser;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类说明：
 * @author  ChenXH
 * @date  2018-12-07 15:57:34
 */
@Controller
@RequestMapping(value = "/controller/carDiscount")
public class CarDiscountController extends BaseController {

    /**
     * 方法说明：进入页面
     * @author  ChenXH
     * @date  2018-12-07 15:57:34
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
    	HttpSession session = request.getSession();
        ModelAndView model =  new ModelAndView();
        //根据用户查询汽车优惠活动的信息
        SysUser user = (SysUser)session.getAttribute("user");
        //根据用户信息查询4s店的经销商,根据经销商查询优惠活动
        CarDiscount carDiscount= carDiscountService.getCarDiscountByUserId(user.getUserid());
       
        model.setViewName("/car/carDiscount/list");
        
        String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		basePath = basePath+"common/img/";
		
		if(carDiscount != null){
			 //添加到作用域中
	        model.addObject("firstimg", carDiscount.getFirstimg());
	        model.addObject("secondimg", carDiscount.getSecondimg());
	        model.addObject("thirdimg", carDiscount.getthirdimg());
	       
			carDiscount.setFirstimg(basePath+(carDiscount.getFirstimg() ==null ? "" : carDiscount.getFirstimg()));
			carDiscount.setSecondimg(basePath+(carDiscount.getSecondimg() ==null ? "" : carDiscount.getSecondimg()));
			carDiscount.setthirdimg(basePath+(carDiscount.getthirdimg() ==null ? "" : carDiscount.getthirdimg()));
			//查询小图片
			CarDiscountDetail carDiscountDetail = carDiscountDetailService.getDataByDiscountId(carDiscount.getId());
			//添加到作用域中
			 model.addObject("firstimgsmall", carDiscountDetail.getFirstimgsmall());
			 model.addObject("secondimgsmall", carDiscountDetail.getSecondimgsmall());
			 model.addObject("thirdimgsmall", carDiscountDetail.getThirdimgsmall());
			 
			carDiscountDetail.setFirstimgsmall(basePath+(carDiscountDetail.getFirstimgsmall() ==null ? "" : carDiscountDetail.getFirstimgsmall()));
			carDiscountDetail.setSecondimgsmall(basePath+(carDiscountDetail.getSecondimgsmall() ==null ? "" : carDiscountDetail.getSecondimgsmall()));
			carDiscountDetail.setThirdimgsmall(basePath+(carDiscountDetail.getThirdimgsmall() ==null ? "" : carDiscountDetail.getThirdimgsmall()));
			model.addObject("carDiscountDetail", carDiscountDetail);
		}
		 //添加到作用域中
        model.addObject("carDiscount", carDiscount);
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  ChenXH
     * @date  2018-12-07 15:57:34
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        //调用 查询方法
        List<CarDiscount> carDiscountList=carDiscountService.loadPageList(params);
        //处理数据
        PageInfo<CarDiscount> pageInfo=new PageInfo<CarDiscount>(carDiscountList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  ChenXH
     * @date  2018-12-07 15:57:34
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        CarDiscount carDiscount=new CarDiscount();
        try {
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                carDiscount = carDiscountService.selectByPrimaryKey(entityId);
                // 进行数据准备
                model.addObject("carDiscount",carDiscount);
            }
            //返回视图位置
            model.setViewName("car/carDiscount/form");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  ChenXH
     * @date  2018-12-07 15:57:34
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap
    		,CarDiscount carDiscountSave,CarDiscountDetail carDiscountDetail){
    	HttpSession session = request.getSession();
    	//根据用户查询汽车优惠活动的信息
        SysUser user = (SysUser)session.getAttribute("user");
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        //进行 修改
        if(entityId>0){
            CarDiscount carDiscount=carDiscountService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carDiscount)){
            	carDiscountSave.setId(entityId);
            	carDiscountSave.setUserid(carDiscount.getUserid());
                try {
                    //修改
                    //carDiscountService.updateByPrimaryKey(carDiscount);
                    //更新
                    carDiscountService.update(carDiscountSave,carDiscountDetail);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            //进行数据添加
            //CarDiscount carDiscount=new CarDiscount();
            
            try {
                //新增
                //carDiscountService.insert(carDiscount);
            	String userid = user.getUserid();
            	carDiscountSave.setUserid(userid);
                carDiscountService.addData(carDiscountSave,carDiscountDetail);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  ChenXH
     * @date  2018-12-07 15:57:34
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            CarDiscount carDiscount = carDiscountService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carDiscount)){
                //carDiscount.setIsDel(0);
                try {
                    carDiscountService.updateByPrimaryKey(carDiscount);
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }
    
    @RequestMapping("/uploadFirstPng")
    @ResponseBody
    public HashMap<String, Object> uploadFirstPng(MultipartFile file,HttpServletRequest request){
    	String path = request.getContextPath();
    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/common/img/";
    	//组装报文
    	HashMap<String, Object> hashMap = new HashMap<String,Object>();
    	HashMap<String, Object> dataMap = new HashMap<String, Object>();
    	// 判断文件是否为空
        if (!file.isEmpty()) {
            try {
            	//得到文件分隔符
                String separator = File.separator;
                String picPath2 = System.getProperty("user.dir").replace("bin","webapps"+path)+ File.separator;
                String directory = picPath2 + "common/img" + separator;
                String newPicName = file.getName()+System.currentTimeMillis();
                if (file.getSize() != 0) {
                	String originalFileNameLeft = file.getOriginalFilename();
                    // 新的图片名称
                    newPicName +=  originalFileNameLeft.substring(originalFileNameLeft.lastIndexOf("."));
                    // 新图片，写入磁盘
                    File f = new File(directory, newPicName);
                    if (!f.exists()) {
                        // 先创建文件所在的目录
                        f.getParentFile().mkdirs();
                    }
                    file.transferTo(f);
                    hashMap.put("code", "0");
                	hashMap.put("msg", "上传成功");
                	dataMap.put("src", basePath+newPicName);
                	hashMap.put("data", dataMap);
                }
                return hashMap;
            } catch (Exception e) {
                e.printStackTrace();
                hashMap.put("code", "0");
            	hashMap.put("msg", "上传失败，已存在该图片");
            	dataMap.put("src", "");
            	hashMap.put("data", dataMap);
            	return hashMap;
            }
        }
        return hashMap;
    }

    @RequestMapping("/uploadSecondPng")
    @ResponseBody
    public HashMap<String, Object> uploadSecondPng(MultipartFile file,HttpServletRequest request){
    	String path = request.getContextPath();
    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/common/img/";
    	//组装报文
    	HashMap<String, Object> hashMap = new HashMap<String,Object>();
    	HashMap<String, Object> dataMap = new HashMap<String, Object>();
    	String newPicName = file.getName()+System.currentTimeMillis();
    	
    	//得到文件分隔符
		String separator = File.separator;
		//获取文件名称
		String originalFilename = file.getOriginalFilename();
		
		String picPath = System.getProperty("user.dir").replace("bin", "webapps"+path);
		picPath = picPath+separator+"common"+separator+"img";
		
		File file2 = new File(picPath, newPicName+originalFilename);
		
		//首先查询目录有没有
		if(!file2.exists()){
			file2.mkdirs();
		}
		
		//复制到服务器
		try {
			file.transferTo(file2);
			hashMap.put("code", "0");
			hashMap.put("msg", "上传成功");
			dataMap.put("src", basePath+newPicName+originalFilename);
			hashMap.put("data", dataMap);
			return hashMap;
		} catch (Exception e) {
			e.printStackTrace();
			hashMap.put("code", "0");
			hashMap.put("msg", "上传失败，已存在该图片");
			dataMap.put("src", "");
			hashMap.put("data", dataMap);
			return hashMap;
		}
    }
    
    @RequestMapping("/uploadThirdPng")
    @ResponseBody
    public HashMap<String, Object> uploadThirdPng(MultipartFile file,HttpServletRequest request){
    	String path = request.getContextPath();
    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/common/img/";
    	//组装报文
    	HashMap<String, Object> hashMap = new HashMap<String,Object>();
    	HashMap<String, Object> dataMap = new HashMap<String, Object>();
    	// 判断文件是否为空
        if (!file.isEmpty()) {
            try {
            	//得到文件分隔符
                String separator = File.separator;
                String picPath2 = System.getProperty("user.dir").replace("bin","webapps"+path)+ File.separator;
                String directory = picPath2 + "common/img" + separator;
                String newPicName = file.getName()+System.currentTimeMillis();
                if (file.getSize() != 0) {
                	String originalFileNameLeft = file.getOriginalFilename();
                    // 新的图片名称
                    newPicName +=  originalFileNameLeft.substring(originalFileNameLeft.lastIndexOf("."));
                    // 新图片，写入磁盘
                    File f = new File(directory, newPicName);
                    if (!f.exists()) {
                        // 先创建文件所在的目录
                        f.getParentFile().mkdirs();
                    }
                    file.transferTo(f);
                    hashMap.put("code", "0");
                	hashMap.put("msg", "上传成功");
                	dataMap.put("src", basePath+newPicName);
                	hashMap.put("data", dataMap);
                }
                return hashMap;
            } catch (Exception e) {
                e.printStackTrace();
                hashMap.put("code", "0");
            	hashMap.put("msg", "上传失败，已存在该图片");
            	dataMap.put("src", "");
            	hashMap.put("data", dataMap);
            	return hashMap;
            }
        }
        return hashMap;
    }
    

}
